package controllers;

import play.*;
import play.mvc.*;
import play.data.*;
import models.*;
import play.data.validation.Constraints;
import play.data.format.*;
import views.html.application.*;
import static play.data.Form.*;

import java.util.*;
import play.i18n.*;

public class Application extends Controller {

	// GET

	@With(LogSession.class)
    public static Result index(String language) {
    	List<Movie> movies = Movie.findTrailer(language);
        return ok(index.render(movies, Lang.forCode(language)));
    }

	@With(LogSession.class)
    public static Result about(String language) {
    	return ok(about.render(Lang.forCode(language)));
    }

	@With(LogSession.class)
    public static Result login(String language) {

		String pageBeforeLogin = flash("refuri");

        return ok(
        	login.render(
        		form(Login.class),
				pageBeforeLogin,
        		Lang.forCode(language)
        	)
        );
    }

	public static Result logout(String language) {
		String uuid = session().get("uuid");
		if (uuid != null)
			LogSession.destroySession(uuid);

	    session().clear();
	    flash("success", "logout.success.msg");
	    return redirect(
	        routes.Application.index(language)
	    );
	}


    // POST
    public static Result authenticate(){
    	Form<Login> loginForm = form(Login.class).bindFromRequest();

		String pageBeforeLogin = loginForm.field("redirect").value();
		String lang = loginForm.field("lang").value();

        if(loginForm.hasErrors()) {
            return badRequest(login.render(loginForm, pageBeforeLogin, Lang.forCode(lang)));
        } else {
			User user = User.findByUser(loginForm.get().username);
			String uuid = LogSession.createSession(user.username, user.role);
            session("uuid", uuid);

			pageBeforeLogin = loginForm.get().redirect;

			if( pageBeforeLogin == null)
				return redirect(
					routes.Application.index(lang)
				);

			return redirect(
				pageBeforeLogin
			);
        }
    }

}
